﻿using System;

namespace parts_client
{
	public class SimData
	{
		protected static SimData _Instance = new SimData(0);

		protected float[] _X = null;
		protected float[] _Y = null;
		protected int _N = 0;
		protected float _MinX = 0.0f;
		protected float _MaxX = 100.0f;
		protected float _MinY = 0.0f;
		protected float _MaxY = 100.0f;
		
		protected byte[] _Frame = null;
		protected int _FrameWidth = 0;
		protected int _FrameHeight = 0;

		protected SimData()
		{
		}

		protected SimData(int n)
		{
			_N = n;
			_X = new float[_N];
			_Y = new float[_N];
		}

		protected SimData(int n, float minx, float maxx, float miny, float maxy)
			: this(n)
		{
			_MinX = minx;
			_MaxX = maxx;
			_MinY = miny;
			_MaxY = maxy;
		}
		
		protected SimData(int frameWidth, int frameHeight)
		{
			_FrameWidth = frameWidth;
			_FrameHeight = frameHeight;
			_Frame = new byte[_FrameWidth * _FrameHeight * 4];
		}
		
		public byte[] Frame
		{
			get { return _Frame; }
		}
		
		public int FrameWidth
		{
			get { return _FrameWidth; }
		}
		
		public int FrameHeight
		{
			get { return _FrameHeight; }
		}

		public int N
		{
			get { return _N; }
			set { _Instance = new SimData(value); }
		}

		public float MinX
		{
			get { return _MinX; }
		}

		public float MaxX
		{
			get { return _MaxX; }
		}

		public float MinY
		{
			get { return _MinY; }
		}

		public float MaxY
		{
			get { return _MaxY; }
		}

		public float[] X
		{
			get { return _X; }
		}

		public float[] Y
		{
			get { return _Y; }
		}

		public static SimData GetCurData() { return _Instance; }

		public static void UpdateWorldBounds(float minx, float maxx, float miny, float maxy)
		{
            if (_Instance == null)
            {
                _Instance = new SimData(0, minx, maxx, miny, maxy);
            }
            else
            {
                _Instance._MinX = minx;
                _Instance._MaxX = maxx;
                _Instance._MinY = miny;
                _Instance._MaxY = maxy;
            }
		}

		public static void UpdateParts(int n, float[] x, float[] y)
		{
			if (_Instance == null)
				_Instance = new SimData(n);
			else if (_Instance.N != n)
				_Instance = new SimData(n, _Instance._MinX, _Instance._MaxX, _Instance._MinY, _Instance._MaxY);

			Array.Copy(x, _Instance._X, n);
			Array.Copy(y, _Instance._Y, n);
		}
		
		public static void UpdateFrame(byte[] data, int width, int height)
		{
			if(_Instance == null)
				_Instance = new SimData(width, height);
			else if(_Instance.FrameWidth != width || _Instance.FrameHeight != height)
				_Instance = new SimData(width, height);
			
			Array.Copy (data, _Instance._Frame, width * height * 4);
		}
	}
}
